import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, Drawer, message} from 'antd';
import React, {useRef, useState} from 'react';
import {SortOrder} from "antd/lib/table/interface";
import {
  addApiUsingPOST,
  deleteApiUsingPOST,
  listApiByPageUsingPOST, offlineInterfaceInfoUsingPOST, onlineInterfaceInfoUsingPOST,
  updateApiUsingPOST
} from "@/services/api/apiController";
import CreateModal from "@/pages/Admin/Api/components/CreateModal";
import UpdateModal from "./components/UpdateModal";


const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.Api>();
  const [selectedRowsState, setSelectedRows] = useState<API.Api[]>([]);

  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: any, file: any) => {
    const hide = message.loading('正在添加');
    const params = {
      ...fields,
      file: undefined,
    };
    console.log(params)
    try {
      const res = await addApiUsingPOST(
        params,
        {},
        file,
      );
      hide();
      // message.success('创建成功');
      if (!res?.data) {
        message.error('创建失败');
      } else if (res.code === 0) {
        message.success('创建成功！');
      } else {
        message.error('创建失败：' + res.message);
      }
      handleModalOpen(false);
      return true;
    } catch (error: any) {
      hide();
      message.error('创建失败.' + error.message);
      return false;
    }
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: any, file: any) => {
    if (!currentRow) {
      message.error('获取信息失败')
      return;
    }
    const hide = message.loading('修改中');
    const params = {
      ...fields,
      id: currentRow.id,
      file: undefined,
    };
    try {
      await updateApiUsingPOST(params, {}, file);
      hide();
      message.success('修改成功');
      return true;
    } catch (error: any) {
      hide();
      message.error('修改失败. ' + error.message);
      return false;
    }
  };

  /**
   *  onLine node
   * @zh-CN 发布接口
   *
   * @param selectedRows
   */
  const handleOffline = async (record: API.IdRequest) => {
    const hide = message.loading('下线中');
    if (!record) return true;
    try {
      await offlineInterfaceInfoUsingPOST({
        id: record.id,
      });
      hide();
      message.success('下线成功');
      actionRef.current?.reload();  //自动刷新
      return true;
    } catch (error: any) {
      hide();
      message.error('下线失败. ' + error.message);
      return false;
    }
  };


  /**
   *  onLine node
   * @zh-CN 发布接口
   *
   * @param selectedRows
   */
  const handleOnline = async (record: API.IdRequest) => {
    const hide = message.loading('发布中');
    if (!record) return true;
    try {
      await onlineInterfaceInfoUsingPOST({
        id: record.id,
      });
      hide();
      message.success('发布成功');
      actionRef.current?.reload();  //自动刷新
      return true;
    } catch (error: any) {
      hide();
      message.error('发布失败. ' + error.message);
      return false;
    }
  };


  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (record: API.Api) => {
    const hide = message.loading('正在删除');
    if (!record) return true;
    try {
      await deleteApiUsingPOST({
        id: record.id,
      });
      hide();
      message.success('删除成功');
      actionRef.current?.reload();  //自动刷新
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败. ' + error.message);
      return false;
    }
  };


  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns: ProColumns<API.Api>[] = [
    {
      dataIndex: 'id',
      valueType: 'indexBorder',
    },
    {
      title: '接口名称',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: {
        rules: [{
          required: true,
        }]
      },

    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: 'textarea',
    },
    {
      title: 'url',
      dataIndex: 'url',
      valueType: 'text',
      formItemProps: {
        rules: [{
          required: true,
        }]
      },
      hideInTable: true,
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      valueType: 'text',
      formItemProps: {
        rules: [{
          required: true,
        }]
      },
    },
    {
      title: '请求参数示例',
      dataIndex: 'requestParams',
      valueType: 'jsonCode',
      formItemProps: {
        rules: [{
          required: true,
        }]
      },
      hideInTable: true,
    },
    {
      title: '请求头',
      dataIndex: 'requestHeader',
      valueType: 'jsonCode',
      hideInTable: true,
    },
    {
      title: '响应头',
      dataIndex: 'responseHeader',
      valueType: 'jsonCode',
      hideInTable: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '关闭',
          status: 'Default',
        },
        1: {
          text: '开启',
          status: 'Processing',
        },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            setCurrentRow(record);
            handleUpdateModalOpen(true);
          }}
        >
          修改
        </a>,
        record.status === 0 ? <Button
          type='text'
          key='online'
          onClick={() => {
            handleOnline(record)
          }}
        >
          发布
        </Button> : null,
        record.status === 1 ? <Button
          type='text'
          danger
          key="offline"
          onClick={() => {
            handleOffline(record);
          }}
        >
          下线
        </Button> : null,
        <Button
          type='text'
          danger
          key="remove"
          onClick={() => {
            handleRemove(record);
          }}>
          删除
        </Button>,
      ],
    },
  ];
  return (
    <PageContainer>
      <div style={{maxHeight: 'calc(100vh - 220px)',minHeight: 'calc(100vh - 220px)', overflow: 'auto'}}>
        <ProTable<API.Api, API.BaseResponsePageApi_>
          headerTitle={'查询表格'}
          actionRef={actionRef}
          rowKey="key"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                handleModalOpen(true);
              }}
            >
              <PlusOutlined/> 新建
            </Button>,
          ]}
          request={async (
            params,
            sort: Record<string, SortOrder>,
            filter: Record<string, React.ReactText[] | null>,
          ) => {
            const res: any = await listApiByPageUsingPOST({
              ...params,
            });
            if (res?.data) {
              return {
                data: res?.data.records || [],
                success: true,
                total: res?.data.total || 0,
              };
            } else {
              return {
                data: [],
                success: false,
                total: 0,
              };
            }
          }}
          columns={columns}
          pagination={{
            pageSize: 8,
          }}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />
      </div>
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万
              </span>
            </div>
          }
        >
          {/*<Button*/}
          {/*  onClick={async () => {*/}
          {/*    await handleRemove(selectedRowsState);*/}
          {/*    setSelectedRows([]);*/}
          {/*    actionRef.current?.reloadAndRest?.();*/}
          {/*  }}*/}
          {/*>*/}
          {/*  批量删除*/}
          {/*</Button>*/}
          {/*<Button type="primary">批量审批</Button>*/}
        </FooterToolbar>
      )}
      <UpdateModal
        onSubmit={async (value, file) => {
          const success = await handleUpdate(value, file);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        visible={updateModalOpen}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.Api>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.Api>[]}
          />
        )}
      </Drawer>
      <CreateModal onCancel={() => {
        handleModalOpen(false)
      }} onSubmit={(values, file) => {
        handleAdd(values, file);
      }} visible={createModalOpen}/>
    </PageContainer>
  );
};
export default TableList;
